package com.taru.order.util;




import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author songzt
 * @version 1.0
 * @date 2020/8/26 14:43
 */
public class JwtUtil {

    private static final String JWTSECRET = "myScrect";//秘钥只有服务端知道
    private static final String ISSUER = "lanqiao";

    /**
     * 生成token-10天
     *
     * @param userId
     * @return
     */
    public static String createToken(String userId)  throws Exception {

        //签发token
        String token;
        try {
            //当前时间的毫秒数
            long currentTimes = System.currentTimeMillis();
            //header
            Map<String,Object> header =new HashMap<String,Object>();
            header.put("typ","JWT");
            header.put("alg","HS256");
            token = JWT.create().   //物理上Header不是必须的
                    withHeader(header).
                    withSubject(userId).withExpiresAt(new Date(currentTimes + 1000 * 60 * 60 * 24 * 10)).
                    withIssuedAt(new Date(currentTimes)).
                    withIssuer(ISSUER).
                    sign(Algorithm.HMAC256(JWTSECRET));
        } catch (Exception ex) {
            throw new Exception("生成Token失败");
        }

        return token;
    }


    /**
     * 解析token(验证)
     * 验证Token合法 的唯一方式就是看是否出现异常
     *
     * @param token
     * @return
     */
    public static String verifyToken(String token) throws Exception {
        String userId;
        try{
            //构件验证器
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(JWTSECRET)).withIssuer(ISSUER).build();
            DecodedJWT decoder = verifier.verify(token);
            userId = decoder.getSubject();
        }catch (Exception  ex){
            throw new Exception("鉴定Token失败");
        }
        return userId;
    }
}
